<route lang="jsonc" type="page">
{
  "style": {
    "navigationBarTitleText": "游戏统计",
    "navigationBarBackgroundColor": "#fd79a8",
    "navigationBarTextStyle": "white"
  }
}
</route>

<template>
  <view class="stats-page">
    <!-- 本局统计卡片 -->
    <view class="stats-card">
      <view class="card-header">
        <text class="card-title">本局战绩</text>
        <text class="game-result" :class="gameResultClass">{{ gameResultText }}</text>
      </view>
      
      <view class="stats-grid">
        <view class="stat-item">
          <text class="stat-value">{{ currentGameStats.score }}</text>
          <text class="stat-label">最终得分</text>
        </view>
        <view class="stat-item">
          <text class="stat-value">{{ currentGameStats.eliminatedCount }}</text>
          <text class="stat-label">消灭总数</text>
        </view>
        <view class="stat-item">
          <text class="stat-value">{{ currentGameStats.maxCombo }}</text>
          <text class="stat-label">最高连击</text>
        </view>
        <view class="stat-item">
          <text class="stat-value">{{ formatTime(currentGameStats.playTime) }}</text>
          <text class="stat-label">游戏时长</text>
        </view>
      </view>
      
      <!-- 本局emoji详情 -->
      <view class="emoji-details">
        <text class="section-title">本局消灭详情</text>
        <view class="emoji-list">
          <view 
            class="emoji-item" 
            v-for="emoji in currentGameStats.emojiDetails" 
            :key="emoji.emojiChar"
          >
            <text class="emoji-char">{{ formatEmojiChar(emoji.emojiChar, emoji.emojiUnicode) }}</text>
            <text class="emoji-count">{{ emoji.eliminatedCount }}个</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 个人统计卡片 -->
    <view class="stats-card" v-if="userStats">
      <view class="card-header">
        <text class="card-title">个人统计</text>
      </view>
      
      <view class="stats-grid">
        <view class="stat-item">
          <text class="stat-value">{{ userStats.totalPlayCount }}</text>
          <text class="stat-label">总局数</text>
        </view>
        <view class="stat-item">
          <text class="stat-value">{{ userStats.bestScore }}</text>
          <text class="stat-label">最高分</text>
        </view>
        <view class="stat-item">
          <text class="stat-value">{{ userStats.maxCombo }}</text>
          <text class="stat-label">最高连击</text>
        </view>
        <view class="stat-item">
          <text class="stat-value">{{ formatTime(userStats.totalPlayTime) }}</text>
          <text class="stat-label">总时长</text>
        </view>
      </view>
      
      <!-- 个人最喜欢的emoji -->
      <view class="emoji-details">
        <text class="section-title">我的最爱 Emoji Top 5</text>
        <view class="top-emoji-list">
          <view 
            class="top-emoji-item" 
            v-for="(emoji, index) in userStats.topEmojiStats" 
            :key="emoji.emojiChar"
          >
            <text class="emoji-rank">{{ index + 1 }}</text>
            <text class="emoji-char">{{ emoji.emojiChar }}</text>
            <text class="emoji-count">{{ emoji.eliminatedCount }}次</text>
            <text class="emoji-percentage">{{ emoji.percentage.toFixed(1) }}%</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 全球统计卡片 -->
    <view class="stats-card" v-if="globalStats">
      <view class="card-header">
        <text class="card-title">全球统计</text>
      </view>
      
      <view class="stats-grid">
        <view class="stat-item">
          <text class="stat-value">{{ globalStats.totalUsers }}</text>
          <text class="stat-label">总玩家</text>
        </view>
        <view class="stat-item">
          <text class="stat-value">{{ globalStats.todayActiveUsers }}</text>
          <text class="stat-label">今日活跃</text>
        </view>
        <view class="stat-item">
          <text class="stat-value">{{ formatNumber(globalStats.totalEliminatedCount) }}</text>
          <text class="stat-label">全球消灭</text>
        </view>
        <view class="stat-item">
          <text class="stat-value">{{ globalStats.globalBestScore }}</text>
          <text class="stat-label">全球最高分</text>
        </view>
      </view>
      
      <!-- 全球热门emoji -->
      <view class="emoji-details">
        <text class="section-title">全球热门 Emoji Top 5</text>
        <view class="top-emoji-list">
          <view 
            class="top-emoji-item" 
            v-for="(emoji, index) in globalStats.popularEmojis" 
            :key="emoji.emojiChar"
          >
            <text class="emoji-rank">{{ index + 1 }}</text>
            <text class="emoji-char">{{ emoji.emojiChar }}</text>
            <text class="emoji-count">{{ formatNumber(emoji.eliminatedCount) }}次</text>
            <text class="emoji-percentage">{{ emoji.percentage.toFixed(1) }}%</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 操作按钮 -->
    <view class="action-buttons">
      <button class="action-btn primary" @click="playAgain">再来一局</button>
      <button class="action-btn secondary" @click="viewRanking">查看排行榜</button>
      <button class="action-btn secondary" @click="backToGame">返回游戏</button>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, onMounted, computed } from 'vue'
import { httpGet } from '@/http/http'

defineOptions({
  name: 'EmojiGameStats'
})

// 当前游戏统计数据
const currentGameStats = ref({
  score: 0,
  eliminatedCount: 0,
  maxCombo: 0,
  playTime: 0,
  gameResult: 'completed',
  emojiDetails: []
})

// 用户统计数据
const userStats = ref(null)

// 全球统计数据
const globalStats = ref(null)

// 加载状态
const loading = ref(true)

// 计算游戏结果样式类
const gameResultClass = computed(() => {
  switch (currentGameStats.value.gameResult) {
    case 'completed':
      return 'result-completed'
    case 'timeout':
      return 'result-timeout'
    case 'quit':
      return 'result-quit'
    default:
      return 'result-default'
  }
})

// 计算游戏结果文本
const gameResultText = computed(() => {
  switch (currentGameStats.value.gameResult) {
    case 'completed':
      return '完成游戏'
    case 'timeout':
      return '时间到'
    case 'quit':
      return '提前退出'
    default:
      return '游戏结束'
  }
})

// 页面挂载时获取统计数据
onMounted(async () => {
  await loadStatsData()
})

// 加载统计数据
async function loadStatsData() {
  try {
    loading.value = true
    
    // 从页面参数获取当前游戏数据
    const pages = getCurrentPages()
    const currentPage = pages[pages.length - 1]
    const options = currentPage.options || {}
    
    if (options.gameData) {
      try {
        currentGameStats.value = JSON.parse(decodeURIComponent(options.gameData))
      } catch (e) {
        console.error('解析游戏数据失败:', e)
      }
    }
    
    // 加载用户统计数据
    await loadUserStats()
    
    // 加载全球统计数据
    await loadGlobalStats()
    
  } catch (error) {
    console.error('加载统计数据失败:', error)
    uni.showToast({
      title: '加载统计数据失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 加载用户统计数据
async function loadUserStats() {
  try {
    const response = await httpGet('/api/miniapp/game/stats/user/emoji_eliminate')
    if (response.code === 200) {
      userStats.value = response.data
    }
  } catch (error) {
    console.error('加载用户统计失败:', error)
  }
}

// 加载全球统计数据
async function loadGlobalStats() {
  try {
    const response = await httpGet('/api/miniapp/game/stats/global/emoji_eliminate')
    if (response.code === 200) {
      globalStats.value = response.data
    }
  } catch (error) {
    console.error('加载全球统计失败:', error)
  }
}

// 格式化时间显示
function formatTime(seconds: number): string {
  if (seconds < 60) {
    return `${seconds}秒`
  } else {
    const minutes = Math.floor(seconds / 60)
    const remainingSeconds = seconds % 60
    return `${minutes}分${remainingSeconds}秒`
  }
}

// 格式化数字显示
function formatNumber(num: number): string {
  if (num >= 100000000) {
    return `${(num / 100000000).toFixed(1)}亿`
  } else if (num >= 10000) {
    return `${(num / 10000).toFixed(1)}万`
  } else if (num >= 1000) {
    return `${(num / 1000).toFixed(1)}k`
  } else {
    return num.toString()
  }
}

// 格式化emoji字符显示
function formatEmojiChar(emojiChar: string, emojiUnicode: string): string {
  // 如果emojiChar存在且不是Unicode编码，直接返回
  if (emojiChar && !emojiChar.match(/^[0-9A-F]+$/i)) {
    return emojiChar
  }
  
  // 否则尝试从Unicode编码转换
  if (emojiUnicode) {
    try {
      const codePoint = parseInt(emojiUnicode, 16)
      return String.fromCodePoint(codePoint)
    } catch (e) {
      console.warn('无法解析emoji Unicode:', emojiUnicode)
      return emojiChar || '❓'
    }
  }
  
  return emojiChar || '❓'
}

// 再来一局
function playAgain() {
  uni.navigateBack({
    delta: 1,
    success: () => {
      // 通过事件通知游戏页面重新开始
      uni.$emit('startNewGame')
    }
  })
}

// 查看排行榜
function viewRanking() {
  uni.navigateTo({
    url: '/pages/relax/game/emoji/ranking'
  })
}

// 返回游戏
function backToGame() {
  uni.navigateBack({
    delta: 1
  })
}
</script>

<style lang="scss" scoped>
.stats-page {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  min-height: 100vh;
  padding: 20rpx;
}

.stats-card {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
  
  .card-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
  }
  
  .game-result {
    padding: 8rpx 16rpx;
    border-radius: 20rpx;
    font-size: 24rpx;
    color: white;
    
    &.result-completed {
      background: #52c41a;
    }
    
    &.result-timeout {
      background: #faad14;
    }
    
    &.result-quit {
      background: #ff4d4f;
    }
    
    &.result-default {
      background: #d9d9d9;
      color: #666;
    }
  }
}

.stats-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20rpx;
  margin-bottom: 30rpx;
}

.stat-item {
  text-align: center;
  padding: 20rpx;
  background: #f5f5f5;
  border-radius: 16rpx;
  
  .stat-value {
    display: block;
    font-size: 32rpx;
    font-weight: bold;
    color: #fd79a8;
    margin-bottom: 8rpx;
  }
  
  .stat-label {
    font-size: 24rpx;
    color: #666;
  }
}

.emoji-details {
  .section-title {
    font-size: 28rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
    display: block;
  }
}

.emoji-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10rpx;
}

.emoji-item {
  display: flex;
  align-items: center;
  background: #f0f0f0;
  padding: 12rpx 20rpx;
  border-radius: 25rpx;
  
  .emoji-char {
    font-size: 32rpx;
    margin-right: 8rpx;
  }
  
  .emoji-count {
    font-size: 24rpx;
    color: #666;
  }
}

.top-emoji-list {
  .top-emoji-item {
    display: flex;
    align-items: center;
    padding: 16rpx 0;
    border-bottom: 1rpx solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    .emoji-rank {
      width: 60rpx;
      font-size: 28rpx;
      font-weight: bold;
      color: #fd79a8;
    }
    
    .emoji-char {
      font-size: 40rpx;
      margin-right: 20rpx;
    }
    
    .emoji-count {
      flex: 1;
      font-size: 28rpx;
      color: #333;
    }
    
    .emoji-percentage {
      font-size: 24rpx;
      color: #999;
    }
  }
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
  padding: 20rpx 0;
}

.action-btn {
  padding: 24rpx;
  border-radius: 12rpx;
  font-size: 32rpx;
  font-weight: bold;
  border: none;
  
  &.primary {
    background: #fd79a8;
    color: white;
  }
  
  &.secondary {
    background: rgba(255, 255, 255, 0.8);
    color: #333;
    border: 2rpx solid #ddd;
  }
  
  &:active {
    opacity: 0.8;
  }
}
</style>